package com.cryptoneedle.garden.spring;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * JPA配置类
 * 配置PostgreSQL为主数据源的JPA配置
 *
 * @author CryptoNeedle
 * @date 2025-10-31
 */
@Configuration
@EnableTransactionManagement
@EntityScan(basePackages = {
        "com.cryptoneedle.garden.entity.doris",
})
@EnableJpaRepositories(basePackages = {
        "com.cryptoneedle.garden.repository.doris",
},
        entityManagerFactoryRef = "dorisEntityManagerFactory",
        transactionManagerRef = "dorisTransactionManager")
public class JpaDorisConfig {
    /**
     * Doris EntityManagerFactory
     */
    @Bean(name = "dorisEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean dorisEntityManagerFactory(
            EntityManagerFactoryBuilder builder,
            @Qualifier("dorisDataSource") DataSource dorisDataSource) {

        Map<String, Object> properties = new HashMap<>();
        properties.put("hibernate.hbm2ddl.auto", "none"); // Doris 系统表只读，使用 validate
        properties.put("hibernate.show_sql", false);
        properties.put("hibernate.dialect", "org.hibernate.dialect.MySQL8Dialect"); // Doris 兼容 MySQL 协议

        return builder
                .dataSource(dorisDataSource)
                .packages("com.cryptoneedle.garden.entity.doris") // 专门存放 Doris 实体
                .persistenceUnit("doris")
                .properties(properties)
                .build();
    }

    /**
     * Doris TransactionManager
     */
    @Bean(name = "dorisTransactionManager")
    public PlatformTransactionManager dorisTransactionManager(
            @Qualifier("dorisEntityManagerFactory") LocalContainerEntityManagerFactoryBean dorisEntityManagerFactory) {
        return new JpaTransactionManager(dorisEntityManagerFactory.getObject());
    }
}